<!--  -->
<template>
  <div class="app-container">
    <el-form inline size="small">
      <!-- 左边为新增按钮 中间是 供应商名称、选择日期范围  右侧为查询按钮 -->
      <el-button
        class="mr10"
        type="primary"
        size="small"
        @click="onAddClick"
        icon="el-icon-plus"
      >新增
      </el-button
      >
      <el-form-item label="采购单编号">
        <el-input
          v-model="params.purchaseOrderCode"
          clearable
          placeholder="请输入采购单编号"
        ></el-input>
      </el-form-item>
      <!-- 采购员 -->
      <el-form-item label="采购员">
        <el-input
          v-model="params.purchaseName"
          placeholder="请输入采购员名称"
        ></el-input>
      </el-form-item>
      <!-- 平台渠道 选择器 使用维护的数组 -->
      <!-- <el-form-item label="平台渠道">
        <el-select
          v-model="params.platformChannels"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in platformChannel"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <!--是否扣库存 是、否 -->
      <!-- <el-form-item label="是否扣库存" clearable>
        <el-select v-model="params.deductStock" clearable placeholder="请选择">
          <el-option label="是" value="是"></el-option>
          <el-option label="否" value="否"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="单据日期">
        <el-date-picker
          type="daterange"
          v-model="invoicesDateSearch"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 交货日期 -->
      <el-form-item label="交货日期">
        <el-date-picker
          type="daterange"
          value-format="yyyy-MM-dd"
          v-model="deliveryDateSearch"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-button
        class="ml10"
        @click="getList"
        type="primary"
        size="small"
        icon="el-icon-search"
      >查询
      </el-button
      >
    </el-form>
    <el-table :data="data" border stripe style="width: 100%; margin-top: 10px" @row-dblclick="handleSelect">
      <el-table-column prop="purchaseOrderCode" label="采购单编号" fixed/>
      <el-table-column prop="vendorName" label="供应商名称"/>
      <el-table-column prop="purchaseName" label="采购员"/>
      <el-table-column prop="invoicesDate" label="单据日期"/>
      <el-table-column prop="deliveryDate" label="交货日期"/>
      <el-table-column prop="purchaseUse" label="采购用途">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.purchase_use"
            :value="scope.row.purchaseUse"
          />
        </template>
      </el-table-column>
      <el-table-column prop="purchaseInStore" label="是否入库">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_yes_no"
            :value="scope.row.purchaseInStore"
          />
        </template>
      </el-table-column>
      <el-table-column prop="platformChannels" label="平台渠道"/>
      <el-table-column prop="orderAmount" label="采购单金额"/>
      <el-table-column label="操作" width="440" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handlePrintForm(scope.row)"
          >打印
          </el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleEditAddForm(scope.row)"
            v-if="scope.row.isMonthly!=='Y'"
          >编辑
          </el-button
          >
          <el-button type="primary" size="mini" @click="handleView(scope.row)"
          >查看
          </el-button
          >
          <el-button type="primary"
                     size="mini"
                     @click="handleIsMonthly(scope.row)"
                     v-if="scope.row.isMonthly!=='Y'"
          >月结
          </el-button
          >
          <el-button type="primary"
                     size="mini"
                     @click="handleIsPayment(scope.row)"
                     v-if="scope.row.isPayment!=='Y'"
          >确认付款
          </el-button
          >
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-row>
        <el-col>
          当前页金额：<font style="color: orange">￥{{ pageTotal }}</font>
          总金额：<font style="color: orange">￥{{ totalPrice }}</font>
        </el-col>
      </el-row>
      <el-pagination
        @size-change="onSizeChange"
        @current-change="onCurrentPageChange"
        :current-page="params.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="params.total"
      ></el-pagination>
    </div>
    <el-dialog
      title="采购单新增/编辑"
      width="900px"
      class="form-container"
      :visible.sync="visible"
    >
      <el-form
        inline
        ref="form"
        size="small"
        :model="addForm"
        :rules="rules"
        :disabled="isView"
        label-width="7em"
        class="add-form"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="采购单编号"
              prop="purchaseOrderCode"
              class="purchaseOrderCode is-required"
            >
              <div style="display: flex; align-items: center">
                <el-input
                  v-model="addForm.purchaseOrderCode"

                  placeholder="请输入采购单编号"
                />
                <!-- 是否自动生成开关 -->
                <el-switch
                  style="margin-left: 10px"
                  @change="onAutoGenerateChange"
                  v-model="addForm.isAutoGenerate"
                />
                <span style="flex: 1">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-select
                v-model="addForm.vendorName"
                filterable
                :remote="true"
                placeholder="请选择供应商"
                style="width: 86%"
                :remote-method="querySearch"
                @change="handleSelectInputVendor"
                :loading="vendorLoading"
              >
                <el-option
                  v-for="item in vendorList"
                  :key="item.value"
                  :label="item.vendorName"
                  :value="item.vendorName"
                />
              </el-select>
              <i
                class="el-icon-search"
                v-if="!isView"
                @click="showSelectClientDialog = true"
                style="
                margin-left: 10px;
                font-size: 20px;
                font-weight: bold;
                cursor: pointer;
              "
              ></i>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销售单编号" prop="salseOrderCode">
              <el-select
                v-model="addForm.salseOrderCode"
                filterable
                :remote="true"
                placeholder="请选择销售单"
                style="width: 86%"
                :remote-method="querySearchSales"
                @change="handleSelectSalesInput"
                :loading="salesLoading"
              >
                <el-option
                  v-for="item in salesList"
                  :key="item.salseOrderCode"
                  :label="item.salseOrderCode"
                  :value="item.salseOrderCode"
                />
              </el-select>
              <i
                class="el-icon-search"
                v-if="!isView"
                @click="showSelectSalesDialog = true"
                style="
                margin-left: 10px;
                font-size: 20px;
                font-weight: bold;
                cursor: pointer;
              "
              ></i>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购员" prop="purchaseName">
              <el-input
                v-model="addForm.purchaseName"
                placeholder="请输入采购员名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 采购用途-->
            <el-form-item label="采购用途" prop="purchaseUse">
              <el-select
                v-model="addForm.purchaseUse"
                placeholder="请选择采购用途"
              >
                <el-option
                  v-for="dict in dict.type.purchase_use"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 供应商供应商供应商邮箱 -->
            <el-form-item label="供应商电话" prop="tel">
              <el-input
                v-model="addForm.tel"
                disabled
                placeholder="请输入供应商电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商邮箱" prop="email">
              <el-input
                v-model="addForm.email"
                disabled
                placeholder="请输入供应商邮箱"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 供应商地址，文本域 2行 -->
            <el-form-item label="供应商地址" style="width: 100%" prop="address">
              <el-input
                type="textarea"
                disabled
                :rows="2"
                style="width: 300px"
                v-model="addForm.address"
                placeholder="请输入供应商地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 采购单日期、交货日期 -->
            <el-form-item label="采购单日期" prop="invoicesDate">
              <el-date-picker
                v-model="addForm.invoicesDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交货日期" prop="deliveryDate">
              <el-date-picker
                v-model="addForm.deliveryDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平台渠道" prop="platformChannels">
              <el-select
                v-model="addForm.platformChannels"
                placeholder="请选择平台渠道"
              >
                <el-option
                  v-for="item in platformChannel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购单金额" prop="orderAmount">
              <el-input
                v-model="addForm.orderAmount"
                placeholder="请输入采购单金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 实收金额 -->
            <el-form-item label="实收金额" prop="actualAmount">
              <el-input
                v-model="addForm.actualAmount"
                placeholder="请输入实收金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 是否入库-->
            <el-form-item label="是否入库" prop="purchaseInStore">
              <el-select
                v-model="addForm.purchaseInStore"
                placeholder="请选择是否入库"
              >
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 附件 -->
            <el-form-item label="附件" prop="attachment">
              <file-upload v-model="addForm.filename"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 备注 -->
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="2"
                style="width: 300px"
                v-model="addForm.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 分割线 -->
      <div style="height: 1px; background-color: #ebeef5; margin: 20px 0"></div>

      <!-- titile:商品信息，右边是选择商品按钮 -->
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 10px;
        "
      >
        <div style="font-size: 16px; font-weight: bold">商品信息</div>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="onAddGoodsClick"
          v-if="!isView"
        >选择物料
        </el-button
        >
      </div>
      <!-- 表格 -->
      <!-- 序号、物料编码、物料名称、规格型号、单位、数量、单价、小计、备注、操作（编辑、删除） -->
      <el-table :data="addForm.orderDetails" border stripe>
        <el-table-column type="index" width="50"/>
        <el-table-column prop="itemCode" label="物料编码"/>
        <el-table-column prop="itemName" label="物料名称"/>
        <el-table-column
          label="产品物料图片"
          prop="itemImage"
          align="center"
          width="100px"
        >
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px; margin-bottom:-4px"
              :src="`${baseUrl}`+scope.row.itemImage"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号"/>
        <el-table-column prop="unitOfMeasure" label="单位"/>
        <el-table-column prop="num" label="数量"/>
        <el-table-column prop="unitPrice" label="单价"/>
        <el-table-column prop="total" label="小计"/>
        <el-table-column prop="remark" label="备注"/>
        <el-table-column label="操作" width="150px" v-if="!isView">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEditGoods(scope.row, scope.$index)"
            >编辑
            </el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDeleteGoods(scope.row)"
            >删除
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <template v-if="!isView">
          <el-button
            type="primary"
            @click="submit"
            v-if="!addForm.purchaseOrderId"
          >新增
          </el-button
          >
          <el-button type="primary" @click="submit" v-else>修改</el-button>
        </template>
      </div>
    </el-dialog>
    <!-- 选择商品弹窗 -->
    <!-- 物料编码、物料名称、规格型号、单位、数量、单价、小计、备注 -->
    <el-dialog
      title="选择商品"
      :visible.sync="showAddGoodsDialog"
      width="500px"
    >
      <el-form
        label-width="7em"
        ref="addGoodsRef"
        size="small"
        :model="addGoodsForm"
        :rules="addGoodsRules"
      >
        <el-form-item label="物料编码" prop="itemCode">
          <el-input
            disabled
            style="width: 90%"
            v-model="addGoodsForm.itemCode"
            clearable
            placeholder="请输入物料编码"
          ></el-input>
          <i
            class="el-icon-search"
            @click="showSelectGoodsDialog = true"
            style="
              margin-left: 10px;
              font-size: 20px;
              font-weight: bold;
              cursor: pointer;
            "
          ></i>
        </el-form-item>

        <el-form-item label="物料名称" prop="itemName">
          <el-input
            disabled
            v-model="addGoodsForm.itemName"
            clearable
            placeholder="请输入物料名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品图片" prop="itemImage">
          <ImageUpload :value="`${baseUrl}`+addGoodsForm.itemImage" @onUploaded="handleImgUplaoded"
                       @onRemoved="handleImgRemoved"
                       :limit="1" :fileSize="1" :fileType="['png','jpg']"
                       title="图片大小不超过156kb，图片格式为PNG"
          />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input
            v-model="addGoodsForm.specification"
            clearable
            disabled
            placeholder="请输入规格型号"
          ></el-input>
        </el-form-item>

        <el-form-item label="单位" prop="unitOfMeasure">
          <el-input
            disabled
            v-model="addGoodsForm.unitOfMeasure"
            clearable
            placeholder="请输入单位"
          ></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="num">
          <el-input
            v-model="addGoodsForm.num"
            clearable
            type="number"
            placeholder="请输入数量"
          ></el-input>
        </el-form-item>

        <el-form-item label="单价" prop="unitPrice">
          <el-input
            v-model="addGoodsForm.unitPrice"
            clearable
            type="number"
            :min="1"
            placeholder="请输入单价"
          ></el-input>
        </el-form-item>

        <el-form-item label="小计" prop="total">
          <el-input
            disabled
            v-model="addGoodsForm.total"
            clearable
            placeholder="请输入小计"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addGoodsForm.remark"
            clearable
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddGoodsDialog = false">取消</el-button>
        <el-button class="ml10" @click="addGoods" type="primary" size="small"
        >确认
        </el-button
        >
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" width="1100px" :visible.sync="showSelectGoodsDialog">
      <mditem :isComponent="true" @select="onSelectGoods"/>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" width="1100px" :visible.sync="showSelectClientDialog">
      <vendor :isComponent="true" @select="onSelectClient"/>
    </el-dialog>
    <!-- 打印弹窗 -->
    <el-dialog :destory-on-close="true" :close-on-click-modal="false" title="打印" width="1100px"
               :visible.sync="showPrintDialog">
      <RIframe v-if="showPrintDialog" :src="currentPrintUrl"/>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" width="1100px" :visible.sync="showSelectSalesDialog">
      <sales :isComponent="true" @select="onSelectSales"/>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import {getToken} from '@/utils/auth'
import mditem from '@/views/mes/md/mditem/index.vue'
import vendor from '@/views/mes/md/vendor/index.vue'
import moment from 'moment'
import {listVendor} from '@/api/mes/md/vendor'
import fileUpload from '@/components/FileUpload/index.vue'
import {genCode} from '@/api/system/autocode/rule'
import RIframe from '@/components/iFrame/index.vue'
import _ from 'lodash'
import {getPurchaseTotal} from '@/api/mes/wm/purchaseOrder'
import sales from "@/views/mes/sale/index.vue";

export default {
  dicts: ['sys_yes_no', 'purchase_use'],
  mounted() {
    this.getList()
    getPurchaseTotal().then(response => {
      this.totalPrice = response.data
    })
  },
  watch: {
    // addGoodsForm.total
    'addGoodsForm.num'(val) {
      this.addGoodsForm.total = val * this.addGoodsForm.unitPrice
    },
    'addGoodsForm.unitPrice'(val) {
      this.addGoodsForm.total = val * this.addGoodsForm.num
    }
  },
  data() {
    return {
      showSelectSalesDialog: false,
      salesLoading: false,
      salesList: [],
      pageTotal: 0.00,
      totalPrice: 0.00,
      showPrintDialog: false,
      currentPrintUrl: '',
      showSelectGoodsDialog: false,
      showSelectClientDialog: false,
      showAddGoodsDialog: false,
      invoicesDateSearch: [],
      deliveryDateSearch: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      addGoodsRules: {
        itemCode: [
          {required: true, message: '请输入物料编码', trigger: 'blur'}
        ],
        itemName: [
          {required: true, message: '请输入物料名称', trigger: 'blur'}
        ],
        // specification: [
        //   { required: true, message: "请输入规格型号", trigger: "blur" },
        // ],
        unitOfMeasure: [
          {required: true, message: '请输入单位', trigger: 'blur'}
        ],
        num: [{required: true, message: '请输入数量', trigger: 'blur'}],
        unitPrice: [{required: true, message: '请输入单价', trigger: 'blur'}],
        remark: [{required: false, trigger: 'blur'}]
      },
      rules: {
        // 判断自动生成是否为true，如果为true则不需要验证
        purchaseOrderCode: [
          {
            validator: (rule, value, callback) => {
              if (this.addForm.isAutoGenerate) {
                callback()
              } else {
                if (!value) {
                  callback(new Error('请输入采购单编号'))
                } else {
                  callback()
                }
              }
            },
            trigger: 'blur'
          }
        ],
        // 供应商电话
        tel: [{required: true, message: '请输入供应商电话', trigger: 'blur'}],
        // 供应商邮箱
        email: [
          {required: true, message: '请输入供应商邮箱', trigger: 'blur'}
        ],
        // 供应商地址
        address: [
          {required: true, message: '请输入供应商地址', trigger: 'blur'}
        ],
        vendorName: [
          {required: true, message: '请选择供应商', trigger: 'blur'}
        ],
        purchaseName: [
          {required: true, message: '请输入采购员', trigger: 'blur'}
        ],
        invoicesDate: [
          {required: true, message: '请选择采购单日期', trigger: 'blur'}
        ],
        deliveryDate: [
          {required: true, message: '请选择交货日期', trigger: 'blur'}
        ],
        platformChannels: [
          {required: true, message: '请选择平台渠道', trigger: 'blur'}
        ],
        // deductStock: [
        //   { required: true, message: "请选择是否扣库存", trigger: "blur" },
        // ],
        // orderAmount: [
        //   { required: true, message: '请输入采购单金额', trigger: 'blur' }
        // ],
        actualAmount: [
          {required: true, message: '请输入实收金额', trigger: 'blur'}
        ]
      },
      params: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        wmProductpurchaseOrder: {}
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload'
      },
      addForm: {
        orderDetails: []
      },
      platformChannel: [
        {
          value: '线下',
          label: '线下'
        },
        {
          value: '1688',
          label: '1688'
        },
        {
          value: '赠送',
          label: '赠送'
        },
        {
          value: '淘宝',
          label: '淘宝'
        },
        {
          value: '拼多多',
          label: '拼多多'
        }
      ],
      goodsTableData: [],
      data: [],
      addGoodsForm: {
        itemCode: '',
        itemName: '',
        specification: '',
        unitOfMeasure: '',
        num: '',
        unitPrice: '',
        total: '',
        remark: ''
      },
      visible: false,
      isView: false,
      isGoodsEdit: false,
      vendorList: [],
      vendorLoading: false
    }
  },
  methods: {
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      this.addGoodsForm.itemImage = imgUrl
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      this.addGoodsForm.itemImage = null
    },
    handleSelect(row) {
      this.$emit("select", row);
    },
    querySearchSales(query) {
      if (query !== '') {
        let params = {
          salesOrderName: query
        }
        request({
          url: '/mes/wm/salseOrder/list',
          method: 'get',
          params
        }).then((res) => {
          this.salesLoading = false
          this.salesList = res.rows
        })
      } else {
        this.salesList = []
      }
    },
    handleSelectSalesInput(val) {
      const sales = this.salesList.find((item) => item.salseOrderCode === val)
      console.log(sales)
      this.onSelectSales(sales)
    },
    onSelectSales(sales) {
      console.log("sales:" + JSON.stringify(sales))

      request({
        url: '/mes/wm/salseOrder/' + sales.salseOrderId,
        method: 'get'
      }).then((res) => {
        this.addForm.orderDetails = res.data.orderDetails;
        let orderAmount = 0
        this.addForm.orderDetails.map((order) => {
          orderAmount = orderAmount + order.total
        })
        this.$set(this.addForm, 'orderAmount', orderAmount)
      })
      this.showSelectSalesDialog = false
      this.$set(this.addForm, 'salseOrderCode', sales.salseOrderCode)
    },
    handleView(row) {
      this.isView = true
      //http://localhost:8080/mes/wm/purchaseOrder/{{purchaseOrderId}}
      request({
        url: '/mes/wm/purchaseOrder/' + row.purchaseOrderId,
        method: 'get'
      }).then((res) => {
        this.addForm = res.data
        this.visible = true
      })
    },
    handleIsMonthly(row) {
      const purchaseOrderCode = row.purchaseOrderCode
      const purchaseOrderId = row.purchaseOrderId
      this.$modal.confirm('是否确认月结采购单编号为"' + purchaseOrderCode + '"的数据项？月结后将不可进行修改')
        .then(function () {
          request({
            url: '/mes/wm/purchaseOrder/updateIsMonthlyOrPayment',
            method: 'put',
            data: {
              purchaseOrderId: purchaseOrderId,
              isMonthly: 'Y',
              isPayment: ''
            }
          }).then((res) => {
            this.addForm = res.data
            this.visible = true
          })
        }).then(() => {
        this.getList()
        this.$modal.msgSuccess('月结成功')
      }).catch(() => {
      })
    },
    handleIsPayment(row) {
      const purchaseOrderCode = row.purchaseOrderCode
      const purchaseOrderId = row.purchaseOrderId
      this.$modal.confirm('是否确认付款采购单编号为"' + purchaseOrderCode + '"的数据项？')
        .then(function () {
          request({
            url: '/mes/wm/purchaseOrder/updateIsMonthlyOrPayment',
            method: 'put',
            data: {
              purchaseOrderId: purchaseOrderId,
              isMonthly: '',
              isPayment: 'Y'
            }
          }).then((res) => {
            this.addForm = res.data
            this.visible = true
          })
        }).then(() => {
        this.getList()
        this.$modal.msgSuccess('确认付款成功')
      }).catch(() => {
      })
    },
    querySearch(query) {
      if (query !== '') {
        listVendor({
          vendorName: query
        }).then((response) => {
          this.vendorLoading = false
          this.vendorList = response.rows
        })
      } else {
        this.vendorList = []
      }
    },

    handleSelectInputVendor(val) {
      //  获取到对应对象
      const vendor = this.vendorList.find((item) => item.vendorName === val)
      this.onSelectClient(vendor)
    },
    onAutoGenerateChange(val) {
      if (this.addForm.isAutoGenerate) {
        genCode('PURCHASE_CODE').then((res) => {
          console.log('====================================')
          console.log(res)
          console.log('====================================')
          this.$set(this.addForm, 'purchaseOrderCode', res)
        })
      } else {
        this.addForm.purchaseOrderCode = ''
      }
    },
    handleEditAddForm(row) {
      this.isView = false
      request({
        url: '/mes/wm/purchaseOrder/' + row.purchaseOrderId,
        method: 'get'
      }).then((res) => {
        this.addForm = res.data
        this.addForm.orderAmount = this.addForm.orderDetails.map(item => item.total).reduce((sum, total) => sum + total, 0);
        this.visible = true
      })
    },
    handlePrintForm(row) {
      this.isView = false
      this.currentPrintUrl = `${location.origin}/prod-api/jmreport/view/908138327178981376?token=Bearer%20eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjlmNzhlMzYzLTJiZjctNGIxMy1hNDk5LTBlODI5NTk3Y2Q0NiJ9.cQRZ8sRJhJry50LN2XcpMW1gOxaMRyrSaEx2MSowxRBntK4HUOQsXcsiNfpMlnFi3uu-uD0677btmTN5Amobkg&purchaseOrderId=${row.purchaseOrderId}`
      this.showPrintDialog = true
    },
    handleEditGoods(row, index) {
      this.addGoodsForm = _.cloneDeep({
        ...row,
        index
      })
      this.isGoodsEdit = true
      this.showAddGoodsDialog = true
    },
    handleFileSuccess(response, file, fileList) {
      console.log('====================================')
      console.log(response)
      console.log('====================================')
      this.upload.open = false
      this.upload.isUploading = false
      // this.$refs.upload.clearFiles();
    },

    onSelectGoods(goods) {
      this.showSelectGoodsDialog = false
      this.addGoodsForm.itemCode = goods.itemCode
      this.addGoodsForm.itemName = goods.itemName
      this.addGoodsForm.itemImage = goods.itemImage
      this.addGoodsForm.specification = goods.specification
      this.addGoodsForm.unitOfMeasure = goods.unitOfMeasure
    },
    onSelectClient(client) {
      this.showSelectClientDialog = false
      this.addForm.vendorName = client.vendorName
      this.addForm.tel = client.tel
      this.addForm.email = client.email
      this.addForm.address = client.address
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    onAddGoodsClick() {
      this.isGoodsEdit = false
      // 清空
      this.addGoodsForm = {
        itemCode: '',
        itemName: '',
        specification: '',
        unitOfMeasure: '',
        num: '',
        unitPrice: '',
        total: '',
        remark: ''
      }
      this.showAddGoodsDialog = true
    },
    addGoods() {
      this.$refs['addGoodsRef'].validate((valid) => {
        if (valid) {
          if (this.isGoodsEdit) {
            // 判断addForm是否有id
            if (this.addGoodsForm.purchaseOrderDetailId) {
              // 修改
              request({
                url: '/mes/wm/productPurchaseOrderDetail',
                method: 'put',
                data: {...this.addGoodsForm}
              }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  })
                  this.addForm.orderDetails = this.addForm.orderDetails.map(
                    (item) => {
                      if (
                        item.purchaseOrderDetailId ===
                        this.addGoodsForm.purchaseOrderDetailId
                      ) {
                        return this.addGoodsForm
                      }
                      return item
                    }
                  )
                  let orderAmount = 0
                  this.addForm.orderDetails.map((order) => {
                    orderAmount = orderAmount + order.total
                  })
                  this.$set(this.addForm, 'orderAmount', orderAmount)
                  this.showAddGoodsDialog = false
                  this.showAddGoodsDialog = false
                } else {
                  this.$message({
                    type: 'error',
                    message: res.msg
                  })
                }
              })
              return
            }

            if (!this.addForm.purchaseOrderId) {
              this.$set(
                this.addForm.orderDetails,
                this.addGoodsForm.index,
                this.addGoodsForm
              )
              this.showAddGoodsDialog = false
            }
          } else {
            if (this.addForm.purchaseOrderId) {
              // 调接口直接添加
              request({
                url: `/mes/wm/productPurchaseOrderDetail/${this.addForm.purchaseOrderCode}/wmProductPurchaseOrderDetail`,
                method: 'post',
                data: {
                  ...this.addGoodsForm,
                  purchaseOrderCode: this.addForm.purchaseOrderCode
                }
              }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '新增成功!'
                  })
                  request({
                    url:
                      '/mes/wm/purchaseOrder/' + this.addForm.purchaseOrderId,
                    method: 'get'
                  }).then((res) => {
                    this.addForm.orderDetails = res.data.orderDetails
                    let orderAmount = 0
                    this.addForm.orderDetails.map((order) => {
                      orderAmount = orderAmount + order.total
                    })
                    this.$set(this.addForm, 'orderAmount', orderAmount)
                    this.showAddGoodsDialog = false
                  })

                  this.showAddGoodsDialog = false
                } else {
                  this.$message({
                    type: 'error',
                    message: res.msg
                  })
                }
              })
            } else {
              this.addForm.orderDetails.push({
                ...this.addGoodsForm
              })
              this.showAddGoodsDialog = false
            }
          }
          let orderAmount = 0
          this.addForm.orderDetails.map((order) => {
            orderAmount = orderAmount + order.total
          })
          this.$set(this.addForm, 'orderAmount', orderAmount)
          console.log('total:' + this.addForm.orderAmount)
        } else {
          return false
        }
      })
    },
    handleDeleteGoods(row) {
      // 提示是否确认
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //  如果不存在id，则直接删除这条
          if (!row.purchaseOrderDetailId) {
            this.addForm.orderDetails = this.addForm.orderDetails.filter(
              (item) => item !== row
            )
            let orderAmount = 0
            this.addForm.orderDetails.map((order) => {
              orderAmount = orderAmount + order.total
            })
            this.$set(this.addForm, 'orderAmount', orderAmount)
            return
          }
          // http://localhost:8080/mes/wm/productpurchaseOrderDetail/{{purchaseOrderDetailId}}
          request({
            url:
              '/mes/wm/productPurchaseOrderDetail/' + row.purchaseOrderDetailId,
            method: 'delete'
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.addForm.orderDetails = this.addForm.orderDetails.filter(
                (item) => item !== row
              )
              let orderAmount = 0
              this.addForm.orderDetails.map((order) => {
                orderAmount = orderAmount + order.total
              })
              this.$set(this.addForm, 'orderAmount', orderAmount)
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleDelete(row) {
      // 提示是否确认删除
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // http://localhost:8080/mes/wm/purchaseOrder/{{purchaseOrderIds}}
          request({
            url: '/mes/wm/purchaseOrder/' + row.purchaseOrderId,
            method: 'delete'
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    onAddClick() {
      this.isView = false
      this.addForm = {
        orderDetails: []
      }
      this.visible = true
      this.addForm.isAutoGenerate = true;
      this.onAutoGenerateChange();
    },
    getList() {
      // startInvoicesDate 单据日期开始时间
      // endInvoicesDate 单据日期结束时间
      // startDeliveryDate 交货日期开始时间
      // endDeliveryDate 交货日期结束时间

      let params = {
        ...this.params
      }
      if (this.invoicesDateSearch.length > 0) {
        params.startInvoicesDate = moment(this.invoicesDateSearch[0]).format(
          'YYYY-MM-DD'
        )
        params.endInvoicesDate = moment(this.invoicesDateSearch[1]).format(
          'YYYY-MM-DD'
        )
      }
      if (this.deliveryDateSearch.length > 0) {
        params.startDeliveryDate = moment(this.deliveryDateSearch[0]).format(
          'YYYY-MM-DD'
        )
        params.endDeliveryDate = moment(this.deliveryDateSearch[1]).format(
          'YYYY-MM-DD'
        )
      }
      request({
        url: '/mes/wm/purchaseOrder/list',
        method: 'get',
        params
      }).then((res) => {
        this.data = res.rows
        let orderAmount = 0;
        this.data.map(
          (item) => {
            orderAmount = orderAmount + item.orderAmount
          });
        this.pageTotal = orderAmount;
        this.params.total = res.total
      })
    },
    onSizeChange(val) {
      this.params.pageSize = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.params.pageNum = val
      this.getList()
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.addForm.purchaseOrderId) {
            // 修改
            request({
              url: '/mes/wm/purchaseOrder',
              method: 'put',
              data: {...this.addForm}
            }).then((res) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.visible = false
                this.getList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })
            return
          }
          // mes/wm/purchaseOrder
          request({
            url: '/mes/wm/purchaseOrder',
            method: 'post',
            data: {...this.addForm}
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '新增成功!'
              })
              this.visible = false
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        } else {
          return false
        }
      })
    }
  },

  components: {
    sales,
    mditem,
    vendor,
    fileUpload,
    RIframe
  },

  computed: {}
}
</script>
<style lang="scss" scoped>
.page {
  text-align: right;
  margin-top: 10px;
}

::v-deep {
  .el-form .el-form--inline {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
  }
}

.form-container {
  ::v-deep {
    .el-form-item {
      min-width: 290px;
      margin-bottom: 15px;
    }

    .el-form-item__content {
      display: inline-flex;
      align-items: center;
    }

    .el-input {
      width: 160px;
    }
  }
}
</style>
